package cn.iocoder.yudao.framework.magic.config.interceptor;

import cn.hutool.core.util.IdUtil;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.modules.db.inteceptor.NamedTableInterceptor;
import org.ssssssss.magicapi.modules.db.model.SqlMode;
import org.ssssssss.magicapi.modules.db.table.NamedTable;

import java.time.LocalDate;
import java.time.LocalDateTime;

import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * 拦截请求
 */
public class TableInterceptorCustom implements NamedTableInterceptor {

    /*
     * 执行单表操作之前
     */
    @Override
    public void preHandle(SqlMode sqlMode, NamedTable namedTable) {
        if (sqlMode == SqlMode.INSERT) {
            // 插入时注入create_by列
            namedTable.column("id", IdUtil.getSnowflakeNextId() );
            namedTable.column("creator", SecurityFrameworkUtils.getLoginUserId());
            namedTable.column("create_time", LocalDateTime.now());
            namedTable.column("tenant_id", SecurityFrameworkUtils.getLoginUser().getTenantId());
        }
        if (sqlMode == SqlMode.UPDATE) {
            // 插入时注入create_by列
            namedTable.column("updater", SecurityFrameworkUtils.getLoginUserId());
            namedTable.column("update_time", LocalDateTime.now());
        }
    }
}
